package com.tms.service.impl;

import com.tms.domain.Location;
import com.tms.mapper.develop.LocationMapper;
import com.tms.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 仓库位业务实现
 *
 * @author ozj
 */
@Service
public class LocationServiceImpl implements LocationService {

    @Autowired
    private LocationMapper locationMapper;

    @Override
    @Cacheable(cacheNames = "locations", key = "#id", unless = "#result == null")
    public Location findLocationById(Integer id) {
        return locationMapper.selectByPrimaryKey(id);
    }

    @Override
    @Cacheable(cacheNames = "locations", key = "#locationName", unless = "#result == null")
    public Location findLocationByName(String locationName, int workcellId) {
        return locationMapper.selectByName(locationName, workcellId);
    }

    @Override
    @Caching(
            put = {
                    @CachePut(cacheNames = "locations", key = "#result.id", unless = "#result == null || #result.id == 0"),
                    @CachePut(cacheNames = "locations", key = "#location.name", unless = "#result == null || #result.id == 0")
            },
            evict = {
                    @CacheEvict(cacheNames = "locationList", allEntries = true, beforeInvocation = true)
            }
    )
    public Location createLocation(Location location) {
        locationMapper.insertSelective(location);
        return location;
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "locations", allEntries = true, beforeInvocation = true),
                    @CacheEvict(cacheNames = "locationList", allEntries = true, beforeInvocation = true)
            }
    )
    public void deleteLocationById(Integer id) {
        locationMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "locationList", allEntries = true, beforeInvocation = true),
                    @CacheEvict(cacheNames = "locations", allEntries = true, beforeInvocation = true)
            }

    )
    public Location updateLocationById(Location location) {
        int result = locationMapper.updateByPrimaryKeySelective(location);
        if (result == 0) {
            throw new RuntimeException("更新失败，更新结果数为0");
        }
        return location;
    }

    @Override
    @Cacheable(cacheNames = "locationList", key = "'allLocations'", unless = "#result == null")
    public List<Location> getAllLocation() {
        return locationMapper.selectAllLocation();
    }
}